﻿using Common;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EC3_6CLH.Model
{
    public class TestConfig
    {
        public ExcelTool Config { get; set; } = new ExcelTool();
        public List<InitParam> InitParams { get; set; } = new List<InitParam>();
        public readonly Dictionary<string, string> ParamList = new Dictionary<string, string>();

        public InitParam? FindParamByName(string name)
        {
            var tmp = InitParams.Where(x => x.Name == name).ToList();
            if (tmp.Count==1)
            {
                return tmp[0];
            }
            return null;
        }

        public InitParam? FindInitParamByName(string name)
        {
            var tmp = InitParams.Where(x => x.Name == name).ToList();
            if (tmp.Count==1)
            {
                return tmp[0];
            }
            return null;
        }

        public void LoadInitParams(string path)
        {
            ExcelPackage.License.SetNonCommercialOrganization("BoYao");
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            using ExcelPackage package = new ExcelPackage(path);
            ExcelWorksheet sheet = package.Workbook.Worksheets["InitParams"];
            InitParams = new List<InitParam>();
            int row = 2;
            while (true)
            {
                ExcelRangeBase cell1 = sheet.Cells[row, 1];
                ExcelRangeBase cell2 = sheet.Cells[row, 2];
                ExcelRangeBase cell3 = sheet.Cells[row, 3];
                ExcelRangeBase cell4 = sheet.Cells[row, 4];
                ExcelRangeBase cell5 = sheet.Cells[row, 5];
                if (cell1.Value == null)
                {
                    break;
                }
                if (string.IsNullOrEmpty(cell1?.Value?.ToString()?.Trim(' ')))
                {
                    break;
                }
                InitParam param = new InitParam()
                {
                    Name =  cell1.Value.ToString(),
                    Index = Convert.ToUInt16(cell2.Value.ToString(), 16),
                    SubIndex  = Convert.ToUInt16(cell3.Value.ToString(), 16),
                    Type = cell4.Value.ToString(),
                    Data  = cell5.Value.ToString()
                };

                InitParams.Add(param);
                row++;
            }
            Config.ParseFile(path, "config");
        }
    }
}